
import { message, Modal } from "antd";
import CardStore from "..";
import DoSubmit from './doSubmit';
import window from '../../../util';
import _ from "lodash";
import cubeUtil from "../../../cubeUtil";
import API from '../../../apis'
import { getQRCode, getBarCode, doExpCardConfig } from '../../../apis/card';
import { action } from "mobx";
import { WeaLocaleProvider, WeaTools } from "ecCom";
import { showExportMenu } from '../../../util/cubeUtil';
const getParent = WeaTools.WindowFunc.getParent;
const getLabel = WeaLocaleProvider.getLabel;

export default class Actions {
    card: CardStore;
    doSubmit: Function;
    submitActions:DoSubmit;
	ecmeDoSubmit: Function;
    constructor(card) {
        this.card = card;
        this.submitActions = new DoSubmit(card);
        this.doSubmit = this.submitActions.execute;
		this.ecmeDoSubmit = this.submitActions.ecmeExecute;//督办建模布局保存用

    }
    runCustomAction = (pageexpandid: string, rVisible?) => {
        try {
            const { function: func } = this.card.cardTab.getRightMenu(pageexpandid);
            if (func) {
                let jsMehtod: string = func.replace('javascript:', 'this.');
                if (jsMehtod.endsWith("()")) {
                    jsMehtod = jsMehtod.split(")").join('') + "'" + pageexpandid + "')";
                }
                if (rVisible) {
                    jsMehtod = jsMehtod.split(")").join('') + "," + rVisible + ")";
                }
                if(jsMehtod.indexOf("doSubmit") > 0){  //新建保存，编辑保存，处理判断回调函数
                    let callbackContent = _.get(this.card.cardTab.urlMap, pageexpandid);
                    // let callbackContent = `/*****fdsafds */function a(id){alert(id);console.log('55')}`;
                    if(callbackContent){
                        let index=callbackContent.lastIndexOf("*/");
                        if(index>=0){
                            callbackContent=callbackContent.substring(index+2);
                        }
                        let callbackfn = callbackContent;
                        if(_.trim(callbackfn)){
                            jsMehtod = jsMehtod.split(")").join('') + ",'',false,"+callbackfn + ")";
                            eval(jsMehtod);
                            return;
                        }
                    }
                }
                eval(jsMehtod);
            }
        } catch (e) {
            message.error("出错:" + e)
            this.card.cardTab.disabled = false;
        }
    }

    toEdit = (pageexpandid) => {
        this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
            this.changeViewType('2');
        });
    }
    doPrint = (pageexpandid) => {
        this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
            this.changeViewType('4', window.openFullWindowHaveBar);
        });
    }
    doBack = () => {
        this.changeViewType('0');
    }
    toDel = (pageexpandid: string, callBack?, rVisible?) => {
        Modal.confirm({
            content: getLabel(383710, '您是否要删除该条数据？'),
            title: getLabel(131329, '信息确认'),
            onOk: () => {
                this.deleteData({
                    ...this.card.params,
                    operate: 'DeleteAction',
                    billids: this.card.params.billid,
                    pageexpandid
                }, () => {
                    if (rVisible) {
                        rVisible();
                    } else if (getParent() && !window.opener && !window._cubeCard) {
                        if (typeof (getParent()['slideflgfun']) == 'function') {
                            if (getParent()['slideflgfun']()) {
                                getParent()['openSlideModalDel']("", "", "");
                            }
                        }
                    } else {
                        if (window._cubeCard && window._cubeCard.delCard) {  //外部调用编辑方法，例如：合同使用建模卡片，操作之后
                            window._cubeCard.delCard();
                            return;
                        }

                        const { boardid, boardgroup, boardcustomid, viewfrom } = this.card.params;
                        if (boardid && boardgroup && boardcustomid) {
                            if(window.opener && window.opener.cubeStore){
                                window.opener.cubeStore.boardStore.doSearch();
                            }
                        }else if(viewfrom == 'fromboarditem' && window.opener && window.opener.cubeStore){
                            window.opener.cubeStore.boardStore.doSearch();
                        }else{
                            //--------------打开的列表数据回调刷新页面-----
                            this.card.cardTab.disabled = false;
                            if (window.opener && window.opener._table && window.opener._table.reLoad) {
                                window.opener._table.reLoad();
                            }else if(window.opener && window.opener.cubeStore){
                                window.opener.cubeStore.Search.refresh();
                            }
                        }
                        window.close();
                    }
                });
            }
        });
    }
    @action
    deleteData = (params: any, callback: (data: any) => void) => {
        API.deleteData(params).then(({ status, error, ...data }) => {
            if (status == '1') {
                if(data.pageExpendResult&&data.pageExpendResult.flag=="false"){
                    Modal.error({
                        content:data.pageExpendResult.errmsg
                    })
                    return;
                }
                callback(data);
            } else {
                message.error(error)
                throw error;
            }
        });
    }
    doSubNew = (pageexpandid: string, issystemflag: string) => {
        this.doSubmit(pageexpandid, issystemflag, '3')
    }
    doSubCopy = (pageexpandid: string, issystemflag: string) => {
        this.doSubmit(pageexpandid, issystemflag, '4')
    }
    viewLog = (pageexpandid: string) => {
        const { billid } = this.card.params;
        this.doInterfacesAction(billid, pageexpandid, () => {
            cubeUtil.viewLog(billid, this.card.base.modeName, this.card.base.modeId, '')
        })
    }
    doShare = (pageexpandid) => {
        const { billid } = this.card.params;
        this.doInterfacesAction(billid, pageexpandid, () => {
            this.card.share.update({
                singleVisible: true,
                billid: this.card.params.billid
            });
        });
    }

    @action
    doImportDetail = (id, issystemflag) => {
        if (!this.card.base.billid) {
            Modal.confirm({
                title: getLabel(82873, '请确认'),
                content: <div dangerouslySetInnerHTML={{ __html: getLabel(383711, "您还未保存数据，是否保存?") }}></div>,
                onOk: () => {
                    this.doSubmit(id, issystemflag, "5",false);
                }
            });
        } else {
            this.card.showDetailImport();
        }
    }

    //生成二维码
    createQRCode = (pageexpandid: string) => {
        const { menuName } = this.card.cardTab.getRightMenu(pageexpandid);
        this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
            this.card.customDialog.showCustomDialog(getQRCode, this.card.base, "qrCode", menuName);
        });
    }
    //生成条形码
    createBARCode = (pageexpandid) => {
        const { menuName } = this.card.cardTab.getRightMenu(pageexpandid);
        this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
            this.card.customDialog.showCustomDialog(getBarCode, this.card.base, "barCode", menuName);
        });
    }

    windowOpenOnSelf = (pageexpandid: string) => {
        this.secondConfirmPrompt(pageexpandid, () => {
            this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
                let hreftarget = _.get(this.card.cardTab.urlMap, pageexpandid);
                if (hreftarget) {
                    hreftarget = hreftarget.replace(/\+/g, "%2B");
                    window.location.href = hreftarget;
                } else {
                    message.error(getLabel('383713', "链接不存在"))
                }
            });
        })
    }
    windowOpenOnNew = (pageexpandid: string) => {
        this.secondConfirmPrompt(pageexpandid, () => {
            this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
                let hreftarget = _.get(this.card.cardTab.urlMap, pageexpandid);
                if (hreftarget) {
                    hreftarget = hreftarget.replace(/\+/g, "%2B");
                    window.open(hreftarget);
                } else {
                    message.error(getLabel('383713', "链接不存在"))
                }
            });
        })
    }
    doCustomFunction = (pageexpandid: string) => {
        this.secondConfirmPrompt(pageexpandid, () => {
            this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
                let hreftarget = _.get(this.card.cardTab.urlMap, pageexpandid);
                // hreftarget = hreftarget.replace(/\+/g, "%2B");   //将+ 号转换成%2B
                if (hreftarget) {
                    try {
                        eval(hreftarget);
                    } catch (e) {
                        console&&console.log(e)
                        // message.error(getLabel('383714',"链接错误"))
                    }
                } else {
                    message.error(getLabel('383713', "链接不存在"))
                }
            });
        });
    }
    //二次确认提示
    secondConfirmPrompt = (pageexpandid: string, callBackFun: Function) => {
        let confirmContent = _.get(this.card.cardTab.confirmMap, pageexpandid);
        if(confirmContent !== '' && confirmContent !== undefined){
            confirmContent = this.getConfirmInfo(confirmContent);
            if(confirmContent == ''){
                return
            }
        }
        if (_.trim(confirmContent)) {   //页面扩展得二次确认提示
            Modal.confirm({
                title: <div dangerouslySetInnerHTML={{ __html: confirmContent }} />,
                okText: getLabel(382958, '继续'),
                cancelText: getLabel(201, '取消'),
                onOk: () => {
                    callBackFun();
                },
                onCancel() { },
            });
            return;
        }
        callBackFun();
        return true;
    }
    getConfirmInfo=(confirmContent) => {
        let info = '';
        if(confirmContent.startsWith('javascript:getConfirmMessage')){
            let str = confirmContent.substring(confirmContent.indexOf('{')+1,confirmContent.indexOf('}'));
            str = str.replace('return','');
            try{
                info = eval(str);
            }catch(e){
                message.error(getLabel('511399','二次确认提示的js函数有错'));
            }
        }else{
            info = confirmContent;
        }
        return info;
    }
    //执行接口动作
    doInterfacesAction = (billid: string, pageexpandid: string, callBackFun?: Function, params?: any) => {
        const { modeId, formId } = this.card.params;
        API.doInterface({ pageexpandid, billid, modeid: modeId, formid: formId ,...this.card.params}).then(({pageExpendResult,status})=>{
            if(pageExpendResult){
                if(pageExpendResult.haveError){
                    Modal.error({
                        content:pageExpendResult.executeResult.errmsg
                    })
                return;
                }else if(pageExpendResult.flag=="true"&&pageExpendResult.interfacetype&&pageExpendResult.interfacetype=='6'&&pageExpendResult.callbackFun){
                    const callbackFun=pageExpendResult.callbackFun;
                    const esbdata=pageExpendResult.esbdata;
                    eval(callbackFun + "("+esbdata+")");
            }
            }
            this.callfun(callBackFun,params);
        });
    }

    callfun =(callBackFun,params)=>{
        if (callBackFun) {
            if (params) {
                callBackFun(params);
            } else {
                callBackFun();
            }
        }
    }

    changeViewType = (type: string, func?: Function) => {
        const query = { ...this.card.params,billid: this.card.base.billid };
        if (type == '0') {
            delete query.fromImportDetail;
        }
        delete query._key;
        query.type = type;
        delete query.layoutid;
        const queryStr = _.keys(_.mapKeys(query, (value, key) => {
            return `${key}=${value}`;
        })).join("&");
        if (type == "2" || type == "0") {
            if (window._cubeCard && window._cubeCard.editCard) {  //外部调用编辑方法，例如：合同使用建模卡片，操作之后
                window._cubeCard.editCard(query);
                return;
            }
            if (this.card.params && this.card.params.istree) {  //处理树的情况下，是否刷新左侧树，禁止路由跳转
                this.card.reloadSearch(query);
                return
            }
        }
        if (func) {
            // func(`${window.location.pathname}#/main/cube/card?${queryStr}`);
            if(type == "4" && this.card.printEdcUrl && this.card.printEdcUrl != ''){
                let printurl = this.card.printEdcUrl+"&cubePrintKey="+this.card.base.billid;
                func(printurl);
            }else{
                func(`/spa/cube/index.html#/main/cube/card?${queryStr}`);
            }
        } else {
            //window.weaHistory.push({ pathname: `/main/cube/card?${queryStr}` });
            if (this.card.isInline || this.card.isInTree) {
                this.card.reloadSearch(query);
            } else {
                window.weaHistory.push({ pathname: `/main/cube/card?${queryStr}` });
            }
        }
    }
    //保存草稿
    doSubmitDraft = (pageexpandid: string, issystemflag: string,btntype?: string, isRefreshto = true,callBack?:Function) => {
        this.doSubmit(pageexpandid, issystemflag, '99',false,callBack);
    }

    @action
    expCard = (pageexpandid: string) => {
        const { modeId } = this.card.base;
        const { billid } = this.card.params;
        API.doInterface({...this.card.params,pageexpandid:pageexpandid, billid:billid, modeid: modeId}).then(({pageExpendResult,status})=>{
            if (pageExpendResult && pageExpendResult.haveError) {
                Modal.error({
                    content: pageExpendResult.executeResult.errmsg
                })
                return;
            }else{
                doExpCardConfig({ action: 'getExpList', modeid: modeId }).then((data: any) => {
                    try {
                        if (data.ExpList.length > 0) {
                            if (data.ExpList.length == 1) {   //当后台设置了一种导出类型的时候直接导出
                                window.open(`/weaver/weaver.formmode.expcard.servlet.ExpCardServer?action=expcard&fileType=${data.ExpList[0]['key']}&billid=${billid}&modeId=${modeId}&layoutid=${this.card.layoutid}&pageexpandid=${pageexpandid}&doInterface=1`);
                            } else {
                                WeaTools.ls.set('cube_export_type', data.ExpList[0]['key']);
                                showExportMenu(data.ExpList, billid, modeId, "card", "", "", "","",this.card.layoutid);
                            }
                        } else {
                            Modal.info({
                                title: getLabel(17416, '导出'),
                                content: (
                                    <div>
                                        {getLabel('500890', '模块没有设置导出文件类型，请联系管理员！')}
                                    </div>
                                ),
                                onOk() { },
                            });
                        }

                    } catch (error) {

                    }
                })
            }
        });

        // const { modeId, billid, formId } = this.card.base;
        // this.doInterfacesAction(this.card.base.billid, pageexpandid, () => {
        //     window.open(`/weaver/weaver.formmode.excel.ExpCardExcelServer?modeId=${modeId}&formId=${formId}&action=expcard&billid=${billid}`, '_self');
        // });
    }
}
